/**
 * 
 */
package com.aspire.android.heliar.raw.mms;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.aspire.android.heliar.pub.Pub;
import com.aspire.android.heliar.pub.analyzer.mms.StandardMMSAnalyzer;
import com.aspire.android.heliar.raw.RawDataFilter;
import com.aspire.android.heliar.raw.RawDataManager;
import com.aspire.android.heliar.utils.Crypt;

/**
 * @author panglei
 * 
 */
public class MMSDataManager implements RawDataManager<MMS> {

	private List<MMS> mmsCache = null;
	private Map<String, MMS> mmsMap = new HashMap<String, MMS>();

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.aspire.android.heliar.raw.RawDataLoader#get(java.lang.String)
	 */
	@Override
	public MMS get(String id) {
		return MMSParser.loadMMS(Integer.parseInt(id));
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.aspire.android.heliar.raw.RawDataLoader#delete(java.lang.String)
	 */
	@Override
	public void delete(String id) {
		MMS mms = mmsMap.get(id);
		if (mms != null) {
			mmsCache.remove(mms);
			mmsMap.remove(id);
			MMSParser.delete(id);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.aspire.android.heliar.raw.RawDataLoader#list()
	 */
	@Override
	public List<MMS> list() {
		//if (mmsCache == null) {
		mmsCache = MMSParser.listMMS(true);
		refresh();
		//}
		return mmsCache;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.aspire.android.heliar.raw.RawDataLoader#list(com.aspire.android.heliar
	 * .raw.RawDataFilter)
	 */
	@Override
	public List<MMS> list(RawDataFilter<MMS> filter) {
		//if (mmsCache == null) {
		mmsCache = MMSParser.listMMS(true);
		refresh();
		//}

		List<MMS> newMMS = new LinkedList<MMS>();
		for (MMS mms : mmsCache) {
			if (filter.filter(mms)) {
				newMMS.add(mms);
			}
		}

		return newMMS;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.aspire.android.heliar.raw.RawDataManager#reload()
	 */
	@Override
	public List<MMS> reload() {
		mmsCache = MMSParser.listMMS(true);
		refresh();
		return mmsCache;
	}

	private void refresh() {
		for (MMS mms : mmsCache) {
			mmsMap.put(String.valueOf(mms.getId()), mms);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.aspire.android.heliar.raw.RawDataManager#generatePubId(com.aspire
	 * .android.heliar.raw.Raw)
	 */
	@Override
	public String generatePubId(MMS mms) {
		if (mms != null && mms.getSubject() != null) {
			return Crypt.getMD5Str(mms.getSubject());
		}
		return null;
	}

	/* (non-Javadoc)
	 * @see com.aspire.android.heliar.raw.RawDataManager#toPub(com.aspire.android.heliar.raw.Raw)
	 */
	@Override
	public Pub toPub(MMS mms) {
		
		StandardMMSAnalyzer analyzer = new StandardMMSAnalyzer();
		Pub pub = analyzer.analyse(mms);
		pub.setKey(generatePubId(mms));
		return pub;
	}

}
